
#import "WXSSettingViewController.h"
#import "WXSAboutAppViewController.h"
#import "UMSocialWechatHandler.h"
#import <QuartzCore/QuartzCore.h>
#import "UMSocial.h"
#import "WXSLoginViewController.h"
#import "WXSRegisterViewController.h"
#import "WXSModifyViewController.h"
#import <Social/Social.h>

@interface WXSSettingViewController ()<CAAnimationDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (strong, nonatomic) UILabel *versionLabel;
@property (strong, nonatomic) UIView *LoginAlertView;
@property (strong, nonatomic) UIView *coverView;
@property (strong, nonatomic) WXSActivityView *activityView;
@property (strong, nonatomic) UIImageView *bgImgView;
@property (strong, nonatomic) UILabel *userName;
@property (strong, nonatomic) UIImageView *imageV;
@property (strong, nonatomic) NSString *imagePath;

- (void)_initializeAppearance;//初始化
- (void)_showLoginAlertView;//弹出登录框
- (void)_hideLoginAlertView;//隐藏登陆框

@end

@implementation WXSSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(exit:) name:@"ExitStatu" object:nil];
    [self _initializeAppearance];
    [self.view addSubview:self.versionLabel];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showTabBar) name:@"showTabBar" object:nil];
    self.view.backgroundColor = [UIColor clearColor];
    if ([WXSUserModel shareUserValue].isLogin == NO) {
        self.userName.text = @"登录/注册";
        self.imageV.image = [UIImage imageNamed:@"默认头像"];
    }else {
        WXSModifyViewController *modifyVC = [[WXSModifyViewController alloc]init];
        [modifyVC passName:^(NSString *name) {
            self.userName.text = name;
            self.imageV.image = [UIImage imageWithContentsOfFile:self.imagePath];
        }];
    }

    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([WXSUserModel shareUserValue].isLogin == NO) {
        self.userName.text = @"登录/注册";
        self.imageV.image = [UIImage imageNamed:@"默认头像"];
    }else {
        WXSModifyViewController *modifyVC = [[WXSModifyViewController alloc]init];
        [modifyVC passName:^(NSString *name) {
            self.userName.text = name;
        }];
        
        AVQuery *query = [AVQuery queryWithClassName:@"UserInfo"];
        [query whereKey:@"username" equalTo:self.userName.text];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            AVObject *info = objects.firstObject;
            
            AVFile *file = [info objectForKey:@"avatar"];
            [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                self.imageV.image = [UIImage imageWithData:data];
            }];

//            self.imageV.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_imagePath]]];
        }];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}


- (void)_initializeAppearance{
    self.title = @"设一下";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}] ;
    
    _bgImgView = [[UIImageView alloc] init];
    _bgImgView.frame = self.view.bounds;
    _bgImgView.image = [UIImage imageNamed:@"bg"];
    _bgImgView.contentMode = UIViewContentModeScaleAspectFill;
    _bgImgView.userInteractionEnabled = YES;
    [self.view addSubview:self.bgImgView];
    /*
     毛玻璃的样式(枚举)
     UIBlurEffectStyleExtraLight,
     UIBlurEffectStyleLight,
     UIBlurEffectStyleDark
     */
    
    NSArray *titleArray = @[@"分享APP",@"清除录音",@"对您有用，打分鼓励一下",@"关于睡眠记账"];
    
    for (int i = 0; i< 5; i++) {
        UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
        effectView.frame = CGRectMake(0, 70+i*60, kBaseWidth, 50);
        effectView.alpha = 0.3;
        [self.view addSubview:effectView];
        
        UIImageView *nextIV = [[UIImageView alloc]initWithFrame:CGRectMake(kBaseWidth - 30, 85 + i*60, 20, 20)];
        nextIV.image = [UIImage imageNamed:@"next"];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 75+i*60, kBaseWidth, 50);
        btn.backgroundColor = [UIColor clearColor];
        btn.tag = 201 + i;
        [btn addTarget:self action:@selector(jumpToNextVC:) forControlEvents:UIControlEventTouchUpInside];
        
        if (i == 0) {
            
            
            _imageV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 75+i*60, 40, 40)];
            _imageV.image = [UIImage imageNamed:@"默认头像"];
            _imageV.layer.cornerRadius = 20;
            _imageV.layer.masksToBounds = YES;
            _userName = [[UILabel alloc]initWithFrame:CGRectMake(60, 73+i*60, kBaseWidth, 44)];
            _userName.text = @"登录/注册";
            _userName.textColor = [UIColor whiteColor];
            btn.frame = CGRectMake(60, 72, kBaseWidth, 50);
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, 72, 60, 50);
            button.backgroundColor = [UIColor clearColor];
            [button addTarget:self action:@selector(changeAvatar) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:button];
            [self.view addSubview:self.userName];
            [self.view addSubview:self.imageV];
            
        }else{
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 73+i*60, kBaseWidth, 44)];
            label.text = titleArray[i-1];
            label.textColor = [UIColor whiteColor];
            
            [self.view addSubview:label];
        }
        [self.view addSubview:btn];
        [self.view addSubview:nextIV];
    }

}

#pragma mark - private method

- (void)_showLoginAlertView{
    
    [self.view addSubview:self.coverView];
    [self.view addSubview:self.LoginAlertView];
   
    CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    popAnimation.duration = 0.4;
    popAnimation.values = @[[NSValue valueWithCATransform3D:
        CATransform3DMakeScale(0.01f, 0.01f, 0.1f)],
                            [NSValue valueWithCATransform3D:
                             CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                            [NSValue valueWithCATransform3D:
                             CATransform3DMakeScale(0.9f, 0.9f, 1.0f)],
                            [NSValue valueWithCATransform3D:
                             CATransform3DIdentity]];
    popAnimation.keyTimes = @[@0.2f,@0.5f,@0.75f,@1.0f];
    popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]
                                     ];
    [self.LoginAlertView.layer addAnimation:popAnimation forKey:nil];

}

- (void)_hideLoginAlertView{
    self.LoginAlertView.userInteractionEnabled = NO;
    CAKeyframeAnimation *hideAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    hideAnimation.duration = 0.4;
    hideAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                             [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0f, 1.0f, 1.0f)],
                             [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.00f, 0.00f, 0.00f)]];
    hideAnimation.keyTimes = @[@0.2f, @0.5f, @0.75f];
    hideAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                      [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                      [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    hideAnimation.delegate = self;
    hideAnimation.removedOnCompletion = NO;
    hideAnimation.fillMode = kCAFillModeForwards;
    [self.LoginAlertView.layer addAnimation:hideAnimation forKey:nil];

}


- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    self.LoginAlertView.userInteractionEnabled = YES;
    [self.LoginAlertView removeFromSuperview];
    [self.coverView removeFromSuperview];
    [self.LoginAlertView.layer removeAllAnimations];

}

-(void)exit:(NSNotification*)info{
    [WXSUserModel shareUserValue].isLogin = NO;
}

#pragma mark - button action
- (void)changeAvatar{
    if ([WXSUserModel shareUserValue].isLogin == YES) {
        
        UIImagePickerController *imagePickVC = [[UIImagePickerController alloc] init];
        // 设置代理对象
        imagePickVC.delegate = self;
        // 开启编辑模式
        imagePickVC.allowsEditing = YES;
        // 设置媒体类型
        imagePickVC.mediaTypes = @[@"public.image"];
        
        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"请选择" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *actionCamera=[UIAlertAction actionWithTitle:@"打开相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            imagePickVC.sourceType=UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePickVC animated:YES completion:nil];
            
        }];
        
        UIAlertAction *actionPhotoLIbrary=[UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            imagePickVC.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickVC animated:YES completion:nil];
            
        }];
        UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:actionCamera];
        
        [alertController addAction:actionPhotoLIbrary];
        
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        self.LoginAlertView.hidden = NO;
        self.coverView.hidden = NO;
        [self _showLoginAlertView];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
{
    
    NSData *data = UIImageJPEGRepresentation(image, 1);
    NSString *tempPath = NSTemporaryDirectory();
    _imagePath = [tempPath stringByAppendingString:@"Avatar.jpg"];
    [data writeToFile:_imagePath atomically:YES];
    
    AVQuery *query = [AVQuery queryWithClassName:@"UserInfo"];
    [query whereKey:@"username" equalTo:self.userName.text];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        NSArray<AVObject *> *info = objects;
        AVFile *file = [AVFile fileWithName:@"avatar" contentsAtPath:_imagePath];
        AVObject *obj = [AVObject objectWithClassName:@"UserInfo" objectId:info.firstObject.objectId];
        [obj setObject:file forKey:@"avatar"];
        //    [file
        [obj saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                NSLog(@"更新成功");
                self.imageV.image = image;
            }else{
                NSLog(@"error %@",error.description);
            }
        }];
    }];
    
    [self dismissViewControllerAnimated:YES completion:nil];

}

- (void)jumpToNextVC:(id)sender{
    NSInteger i = [sender tag];
    if (i == 201) {
        if ([WXSUserModel shareUserValue].isLogin == NO) {
            self.LoginAlertView.hidden = NO;
            self.coverView.hidden = NO;
           [self _showLoginAlertView];
            
        }else{
            self.LoginAlertView.hidden = YES;
            self.coverView.hidden = YES;
            WXSModifyViewController *modifyVC = [[WXSModifyViewController alloc]init];
            modifyVC.name = self.userName.text;
            [modifyVC passName:^(NSString *name) {
                self.userName.text = name;
            }];
            [self.navigationController pushViewController:modifyVC animated:YES];
            NSLog(@"跳转到修改页面");
        }
        
    }else if (i == 202){
        [self buttonClicked];
        NSLog(@"跳转到分享页面");
    }else if (i == 203){
        NSLog(@"跳转到清理录音界面");
    }else if (i == 204){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/app/id1018221712"]];
        NSLog(@"跳转到AppStore");
    }else{
        WXSAboutAppViewController *aboutVC = [[WXSAboutAppViewController alloc]init];
        [self.navigationController pushViewController:aboutVC animated:YES];
        NSLog(@"跳转到介绍页面");
    }
}

- (void)addButtonClicked:(UIButton *)button{
    ButtonView *bv = [[ButtonView alloc]initWithText:@"新浪微博" image:[UIImage imageNamed:@"share_platform_sina"] handler:^(ButtonView *buttonView){
        NSLog(@"点击新增的新浪微博");
    }];
    [self.activityView addButtonView:bv];
}

- (void)buttonClicked{
    if (!self.activityView) {
        self.activityView = [[WXSActivityView alloc]initWithTitle:@"分享到" referView:self.view];
        
        //横屏会变成一行6个, 竖屏无法一行同时显示6个, 会自动使用默认一行4个的设置.
        self.activityView.numberOfButtonPerLine = 6;
        
        ButtonView *bv = [[ButtonView alloc]initWithText:@"新浪微博" image:[UIImage imageNamed:@"share_platform_sina"] handler:^(ButtonView *buttonView){
            NSLog(@"点击新浪微博");
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"QQ" image:[UIImage imageNamed:@"share_platform_qqfriends"] handler:^(ButtonView *buttonView){
            NSLog(@"点击QQ");
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"微信" image:[UIImage imageNamed:@"share_platform_wechat"] handler:^(ButtonView *buttonView){
                        NSLog(@"点击微信");
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"微信朋友圈" image:[UIImage imageNamed:@"share_platform_wechattimeline"] handler:^(ButtonView *buttonView){
            NSLog(@"点击微信朋友圈");
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:@"友盟社会化分享让您快速实现分享等社会化功能，http://umeng.com/social" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    NSLog(@"分享成功！");
                    [UMSocialData defaultData].extConfig.wechatSessionData.url = @"http://baidu.com";
                    
                }
            }];

        }];
        [self.activityView addButtonView:bv];
        
    }
    
    [self.activityView show];
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)showTabBar{
    self.tabBarController.tabBar.hidden = NO;
}

- (BOOL)shouldAutorotate
{
    return YES;
}

- (void)pushToRegisterVC{
    WXSRegisterViewController *registerVC = [[WXSRegisterViewController alloc]init];
    [self.navigationController pushViewController:registerVC animated:YES];

}

- (void)pushToLoginVC:(id)sender{
    NSInteger i = [sender tag];
    if (i == 301) {
        WXSLoginViewController *loginVC = [[WXSLoginViewController alloc]init];
        [loginVC returnName:^(NSString *passName) {
            self.userName.text = passName;
            if ([WXSUserModel shareUserValue].isLogin == YES) {
                self.LoginAlertView.hidden = YES;
                self.coverView.hidden= YES;
            }else{
                self.LoginAlertView.hidden = NO;
                self.coverView.hidden= NO;
            }
        }];
    [self.navigationController pushViewController:loginVC animated:YES];
   }
}

//- (int)supportedInterfaceOrientations
//{
//    return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscape;
//}

#pragma mark - lazy load

- (UILabel *)versionLabel{
    if (!_versionLabel) {
        _versionLabel = [[UILabel alloc]initWithFrame:CGRectMake(kBaseWidth/2 - 47, kBaesHeight - 100, 120, 30)];
        _versionLabel.text = @"睡眠记账 V1.0.0";
        _versionLabel.textColor = [UIColor lightGrayColor];
        _versionLabel.font = [UIFont systemFontOfSize:14];
    }
    return _versionLabel;
}

- (UIView *)LoginAlertView{
    if (!_LoginAlertView) {

        _LoginAlertView = [[UIView alloc]init];
        _LoginAlertView.frame = CGRectMake(0, 0, kBaseWidth - 20, 260);
        _LoginAlertView.backgroundColor = [UIColor clearColor];
        _LoginAlertView.layer.cornerRadius = 5;
        _LoginAlertView.layer.masksToBounds = YES;
        _LoginAlertView.center = self.view.center;
        
        UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
        UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
        effectView.frame = self.LoginAlertView.bounds;
        effectView.alpha = 0.6f;
        [_LoginAlertView addSubview:effectView];
        
        UIButton *registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        registerBtn.frame = CGRectMake(0, CGRectGetHeight(self.LoginAlertView.bounds)-40, CGRectGetWidth(self.LoginAlertView.bounds), 30);
        [registerBtn setTitleColor:[UIColor colorWithRed:1.000 green:0.437 blue:0.439 alpha:1.000] forState:UIControlStateNormal];
        registerBtn.backgroundColor = [UIColor clearColor];
        [registerBtn setTitle:@"没有账号?注册" forState:UIControlStateNormal];
        registerBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        registerBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [registerBtn addTarget:self action:@selector(pushToRegisterVC) forControlEvents:UIControlEventTouchUpInside];
        
        for (int j = 0; j < 3; j++) {
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(30, 60 + 50*j, CGRectGetWidth(self.LoginAlertView.bounds) - 60, 40)];
            
            view.layer.cornerRadius = 20;
            view.layer.masksToBounds = YES;
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(30, 60 + 50*j, CGRectGetWidth(self.LoginAlertView.bounds) - 60, 40);
            btn.backgroundColor = [UIColor clearColor];
            btn.layer.cornerRadius = 20;
            btn.layer.masksToBounds = YES;
            btn.tag = 301 + j;
            [btn addTarget:self action:@selector(pushToLoginVC:) forControlEvents:UIControlEventTouchUpInside];
            
            UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(view.bounds)/2 - 50, 7, 26, 26)];
            
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetWidth(view.bounds)/2 - 10, 5, 120, 30)];
            label.textColor = [UIColor whiteColor];
            
            if (j == 0) {
                label.text = @"账号登录";
                imageV.image = [UIImage imageNamed:@"account"];
                view.backgroundColor = [UIColor colorWithRed:0.090 green:0.706 blue:0.435 alpha:1.000];

            }else if (j == 1){
                label.text = @"QQ登录";
                imageV.image = [UIImage imageNamed:@"qq"];
                view.backgroundColor = [UIColor colorWithRed:0.220 green:0.639 blue:0.984 alpha:1.000];
            }else{
                label.text = @"微信登录";
                imageV.image = [UIImage imageNamed:@"weixin"];
                 view.backgroundColor = [UIColor colorWithRed:0.977 green:0.774 blue:0.261 alpha:1.000];
            }
            [_LoginAlertView addSubview:view];
            [view addSubview:imageV];
            [view addSubview:label];
            [_LoginAlertView addSubview:btn];
            [_LoginAlertView addSubview:registerBtn];
            
        }
        
        UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancleBtn.frame = CGRectMake(CGRectGetWidth(self.LoginAlertView.bounds) - 27, 5, 26, 26);
        cancleBtn.layer.cornerRadius = 13;
        cancleBtn.layer.masksToBounds = YES;
        [cancleBtn setImage:[UIImage imageNamed:@"cancle"] forState:UIControlStateNormal];
        [cancleBtn addTarget:self action:@selector(_hideLoginAlertView) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.LoginAlertView.bounds)/2 - 35, 10, 80, 30)];
        titleLabel.text = @"登录/注册";
        titleLabel.textColor = [UIColor whiteColor];
        
        [_LoginAlertView addSubview:titleLabel];
        [_LoginAlertView addSubview:cancleBtn];
   
    }
    return _LoginAlertView;
}

- (UIView *)coverView{
    if (!_coverView) {
        _coverView = [[UIView alloc]initWithFrame:self.view.bounds];
    }
    return _coverView;
}

@end
